package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.dao.PmsCategoryDao;
import com.atguigu.gulimall.product.entity.PmsCategoryEntity;
import com.atguigu.gulimall.product.service.PmsCategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.web.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.service.PmsCategoryService;
import org.springframework.transaction.annotation.Transactional;

@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {

    @Autowired
    private PmsCategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>());
        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> listWithTree() {
        List<PmsCategoryEntity> categoryEntities = baseMapper.selectList(null);
        //获取一级分类
        List<PmsCategoryEntity> menus = categoryEntities.stream().filter(v -> v.getParentCid() == 0).map((menu) -> {
            menu.setChildren(this.getChildrens(menu,categoryEntities));
            return menu;
        }).sorted((menu1,menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return menus;
    }

    private List<PmsCategoryEntity> getChildrens(PmsCategoryEntity root, List<PmsCategoryEntity> categoryEntities) {
        List<PmsCategoryEntity> children = categoryEntities.stream().filter(menu -> {
            return menu.getParentCid() == root.getCatId();
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO //检查当前删除菜单是否被其它地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 级联更新所有关联数据
     */
    @CacheEvict(value = "category", key = "'getTopCategory'")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(PmsCategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

        /**同时修改缓存中的数据**/
    }

    //每一个需要缓存的数据都来置顶要放到哪个名字的缓存
    @Cacheable(value = {"category"} ,key = "#root.method.name")  //代表当前方法的结果需要换成，如果缓存中有，方法不调用。如果缓存中没有，会调用方法，最后将方法的结果放入缓存
    @Override
    public List<PmsCategoryEntity> getTopCategory() {
        return baseMapper.selectList(new QueryWrapper<PmsCategoryEntity>().eq("parent_cid", 0L));
    }

    @Override
    public Map<String, List<Catalog2Vo>> listCategoryTree() {
        /**
         * 初次查询、将结果主动缓存到Redis、和注解缓存到Redis
         * 二次查询、不会进入方法、直接从注解缓存获取结果
         */
        /**
         * 预防高并发请求下、缓存击穿、
         */
        Map<String, List<Catalog2Vo>> res = null;
        //从缓存中获取JSON数据
        String key = "categoryTree";
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();

        while (true) {
            //获取结果缓存
            String tree = forValue.get(key);
            //如果缓存不为空、直接解析返回
            if (StringUtils.isNotEmpty(tree)) {
                return JSON.parseObject(tree, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
            }
            //缓存为空、加锁查数据更新缓存
            RLock lock = redissonClient.getLock("categoryTree-lock");
            //拿到锁、就去查询数据库、更新缓存
            if (lock.tryLock()) {
                try {
                    //拿到锁就执行业务、否则循环
                    res = listCategoryTreeFromDB();
                    forValue.set(key, JSON.toJSONString(res));
                } finally {
                    lock.unlock();
                }
                return res;
            }
            //睡上100毫秒
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private Map<String, List<Catalog2Vo>> listCategoryTreeFromDB() {
        //查出所有1级分类
        List<PmsCategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<PmsCategoryEntity>().eq("show_status", 1));
        Map<String, List<Catalog2Vo>> categoryMenu = categoryEntities.stream().filter(v->v.getParentCid() == 0).collect(Collectors.toMap(key -> key.getCatId().toString(), catalog2List -> {
            //获取二级分类
            List<Catalog2Vo> catalog2Vos = categoryEntities.stream().filter(item2 -> item2.getParentCid() == catalog2List.getCatId()).map(catalog2 -> {               //List<Catalog2Vo>      --Catalog2Vo
                Catalog2Vo catalog2Vo = new Catalog2Vo(catalog2List.getCatId().toString(), null, catalog2.getCatId().toString(), catalog2.getName());
                //获取三级分类
                List<Catalog2Vo.Catalog3Vo> category3Menu = categoryEntities.stream().filter(item3 -> item3.getParentCid() == catalog2.getCatId()).map(catalog3 -> {       //List<Catalog2Vo>      --Catalog2Vo.catalog3Vo
                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(catalog2.getCatId().toString(), catalog3.getCatId().toString(), catalog3.getName());
                    return catalog3Vo;
                }).collect(Collectors.toList());
                //录入三级分类
                catalog2Vo.setCatalog3List(category3Menu);
                return catalog2Vo;
            }).collect(Collectors.toList());
            return catalog2Vos;
        }));
        return categoryMenu;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        //递归统计分类路径：父——>子
        List<Long> parentPath = findParentPath(catelogId, paths);
        //排序集合：正序排序
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        //查出当前分类信息
        PmsCategoryEntity byId = this.getById(catelogId);
        //如果当前分类的父ID不为根，查找录入父ID
        if(byId.getParentCid()!=0) {
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }
}